package com.itjh.filter;

import com.alibaba.fastjson.JSONObject;
import com.itjh.pojo.MyResponseResult;
import com.itjh.utils.JwtUtils;
import com.itjh.utils.ThreadLocalUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Description:
 *
 * @Create 2025/1/21 9:33
 */

//@WebFilter(urlPatterns = "/*")
//@Component
public class HeiMa_LoginCheckFilter implements Filter {
//    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 获取用户的请求路径
        String uri = request.getRequestURI(); //获取资源路径:/login
//        String url = request.getRequestURL().toString(); //获取完整路径:http://localhost:8080/login

        //2. 判断请求url中是否包含login，如果包含，说明是登录操作，放行
        if ("/login".equals(uri)) {
            chain.doFilter(request, response);
            return;
        }

        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("token");

        //4. 判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(token)) {
            responseResult(response);
            return;
        }

        //5. 解析token，如果解析失败，返回错误结果（未登录）
        try {
            Map<String, Object> map = jwtUtils.parseJwt(token);
            //6. 如果解析成功，说明已经登录，获取其中的用户信息，将用户信息存入到request作用域中，放行
            ThreadLocalUtils.setValue(map);
            chain.doFilter(request, response);
        } catch (Exception e) {
            responseResult(response);
        }
    }

    private void responseResult(HttpServletResponse response) throws IOException {
        MyResponseResult<Object> responseResult = MyResponseResult.error("NOT_LOGIN");
        //把MyResponseResult对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
        String json = JSONObject.toJSONString(responseResult);
        //响应
        response.getWriter().write(json);
    }
}
